package com.shark.security.jwt.utils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public final class CacheUtil {
	
	private static CacheManager cacheManager;
	
	static {
		cacheManager = SpringUtil.getBean(CacheManager.class);		
	}
	
	/**
	 * 
	 * @param cacheName
	 * @param key
	 * @param o
	 */
	public static void put(String cacheName, String key, Object o) {
		Cache cache = getCache(cacheName);
		Element e = new Element(key, o);
		cache.put(e);
	}
	
	/**
	 * 
	 * @param cacheName
	 * @param key
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T get(String cacheName, String key) {
		Cache cache = getCache(cacheName);
		T objectValue = (T)cache.get(key).getObjectValue();
		return objectValue;
	}
	
	/**
	 * 
	 * @param cacheName
	 * @param key
	 * @return
	 */
	public static boolean remove(String cacheName, String key) {
		Cache cache = getCache(cacheName);
		return cache.remove(key);
	}

	/**
	 * @param cacheName
	 * @return
	 */
	private static Cache getCache(String cacheName) {
		Cache cache = cacheManager.getCache(cacheName);
		if (cache == null) {
			throw new RuntimeException("Cache Name Not Exists");
		}
		return cache;
	}
}
